package de.herberlin.pss.ui;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.util.Arrays;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

import org.apache.log4j.Logger;

import de.herberlin.pss.action.ImportAction;

/**
 * Import new Files form drag and drop
 * @author aherbertz
 *
 */
public class ImportTransferHandler extends TransferHandler {
	
	private static final long serialVersionUID = 1L;
	private Logger logger=Logger.getLogger(getClass());

	@Override
	public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
		//logger.debug("Component="+comp+", DataFlavor[]="+transferFlavors);
		return true;
	}


	@Override
	public boolean importData(JComponent comp, Transferable t) {

		try {
			DataFlavor[] flavors=t.getTransferDataFlavors();
			StringBuffer unknownFlavors=new StringBuffer("Unknown DataFlavor: ");
			for (DataFlavor d : flavors) {
				logger.debug("Flavor="+d.getHumanPresentableName());
				Class repClass=d.getRepresentationClass();
				logger.info("Representing class="+repClass);
				List fileList=null;
				if (String.class.equals(repClass)) {
					// Ubuntu linux
					String td=(String)t.getTransferData(d);
					if (td != null) {
						String[] files=td.split("\n");
						fileList=Arrays.asList(files);
					}
				} else if (List.class.equals(repClass)) {
					// windows vista
					fileList=(List)t.getTransferData(d);
				} else {
					unknownFlavors.append(repClass+ " ");
					logger.warn("Unknown DataFlavor: "+repClass);
					
				}
				logger.warn(unknownFlavors.toString());
				if (fileList!=null) {
					new ImportAction(fileList).start();
					return true;
				}
			}
			Frame.showMessage(unknownFlavors.toString(), null);

		} catch (Exception e) {
			logger.error(e,e);
			Frame.showMessage(e.getLocalizedMessage(), e);
			return false;
		}
		return true;
	}


	private DataFlavor[] _supportedFlavors=null;
	protected DataFlavor[] getSupportedFlavors() {
		
		if (_supportedFlavors==null) {
			_supportedFlavors=new DataFlavor[1];
			_supportedFlavors[0]=new DataFlavor(String.class,"text/uri-list");
		}
		
		return _supportedFlavors;
	}
}
